package org.jeecg.modules.zcgl.tencent.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.service.ISysUserDepartService;
import org.jeecg.modules.zcgl.entity.AssetInfo;
import org.jeecg.modules.zcgl.entity.LeaseContractInfo;
import org.jeecg.modules.zcgl.entity.RepairInfo;
import org.jeecg.modules.zcgl.enums.LeaseContractStatusEnum;
import org.jeecg.modules.zcgl.service.IAssetInfoService;
import org.jeecg.modules.zcgl.service.ILeaseContractInfoService;
import org.jeecg.modules.zcgl.service.IRepairImageService;
import org.jeecg.modules.zcgl.service.IRepairInfoService;
import org.jeecg.modules.zcgl.tencent.config.CheckLogin;
import org.jeecg.modules.zcgl.tencent.service.ICustomerAttentionService;
import org.jeecg.modules.zcgl.tencent.vo.RepairAsseVo;
import org.jeecg.modules.zcgl.vo.RepairInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

/**
 * @Description: 维修信息
 * @Version: V1.0
 */
@Api(tags = "维修信息")
@RestController
@RequestMapping("/tencent/repairInfo")
@Slf4j
public class WxRepairInfoController {


    @Autowired
    private ISysBaseAPI sysBaseAPI;

//	@Value(value = "${jeecg.path.upload}")
//	private String uploadpath;
//
//	/**
//	 * 本地：local minio：minio 阿里：alioss
//	 */
//	@Value(value="${jeecg.uploadType}")
//	private String uploadType;

    @Autowired
    private IRepairInfoService repairInfoService;
    @Autowired
    private IRepairImageService repairImageService;
    @Autowired
    private ILeaseContractInfoService leaseContractInfoService;
    @Autowired
    private ICustomerAttentionService customerAttentionService;
    @Autowired
    private IAssetInfoService assetInfoService;
    @Autowired
    private ISysUserDepartService userDepartService;


    @Value("${message.temp.asset_repair:asset_repair}")
    private String assetRepairMessageTemp;

    /**
     * 安全维修部编号
     */
    @Value("${message.temp.maintain_depart_code:0000000100090004}")
    private String maintainDepartCode;

//	@CheckLogin
//	@RequestMapping("/uploadFile")
//	public Result<String> uploadFile(HttpServletRequest request, @RequestParam("file")MultipartFile [] files){
//
//		// 这样就可以收到文件了，files.length == 1.
//		System.out.println(files.length);
//
//		// 后续操作省略
//		return Result.error("sss");
//	}

    @CheckLogin
    @PostMapping(value = "/upload")
    public Result<String> upload(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        String attentionId = JwtUtil.getUserNameByToken(request);
        String bizPath = request.getParameter("biz");
        if (StringUtils.isBlank(bizPath)) {
            bizPath = "wx" + File.separator + attentionId;
        } else {
            bizPath = "wx" + File.separator + bizPath + File.separator + attentionId;
        }
        String savePath = sysBaseAPI.upload(file, bizPath);
        if (oConvertUtils.isNotEmpty(savePath)) {
            return Result.ok(savePath);
        } else {
            return Result.error("上传失败！");
        }
    }

    /**
     * 分页列表查询
     *
     * @param repairInfo
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
//	@AutoLog(value = "维修信息-分页列表查询")
    @CheckLogin
    @ApiOperation(value = "维修信息-分页列表查询", notes = "维修信息-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<RepairInfo>> queryPageList(RepairInfo repairInfo,
                                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                   HttpServletRequest req) {
        repairInfo.setAttentionId(JwtUtil.getUserNameByToken(req));
        QueryWrapper<RepairInfo> queryWrapper = QueryGenerator.initQueryWrapper(repairInfo, req.getParameterMap());
        queryWrapper.orderByDesc("id");
        Page<RepairInfo> page = new Page<RepairInfo>(pageNo, pageSize);
        IPage<RepairInfo> pageList = repairInfoService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param vo
     * @return
     */
//	@AutoLog(value = "维修信息-添加")
    @CheckLogin
    @ApiOperation(value = "维修信息-添加或者修改", notes = "维修信息-添加或者修改")
    @PostMapping(value = "/saveOrUpdate")
    public Result<?> saveOrUpdate(@RequestBody RepairInfoVo vo, HttpServletRequest req) {
        String attentionId = JwtUtil.getUserNameByToken(req);
        vo.setAttentionId(attentionId);
        boolean bool = repairInfoService.wxSaveOrUpdateByVo(vo);
        if (StringUtils.isBlank(vo.getId()) && bool) {
            //查询出安全维修部 部门下的所有用户ID
            List<String> userIds = userDepartService.queryUserIdsByDepCode(maintainDepartCode);
            //查询资产信息
            AssetInfo assetInfo = assetInfoService.getById(vo.getAssetId());
            //判断资产是否存在并且有管理员
            if (assetInfo != null && StringUtils.isNotBlank(assetInfo.getManagerId())) {
                if (!userIds.contains(assetInfo.getManagerId())) {
                    userIds.add(assetInfo.getManagerId());
                }
            }
            //判断用户ID是否有，并发送系统消息
            if (userIds != null && userIds.size() > 0) {
                Map<String, String> map = new HashMap<>();
                map.put("assetName", assetInfo.getAssetName());
                map.put("repairTitle", vo.getRepairTitle());
                sysBaseAPI.sendSysAnnouncement("系统", userIds, null, map, assetRepairMessageTemp);
            }
        }
        return Result.ok("操作成功！");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
//	@AutoLog(value = "维修信息-通过id删除")
    @CheckLogin
    @ApiOperation(value = "维修信息-通过id删除", notes = "维修信息-通过id删除")
    @PostMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        repairInfoService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
//	@AutoLog(value = "维修信息-批量删除")
    @CheckLogin
    @ApiOperation(value = "维修信息-批量删除", notes = "维修信息-批量删除")
    @PostMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.repairInfoService.removeByIds(Arrays.asList(ids.split(CommonConstant.DEFAULT_SEPARATOR)));
        return Result.ok("删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
//    @AutoLog(value = "维修信息-通过id查询")
    @ApiOperation(value = "维修信息-通过id查询", notes = "维修信息-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<RepairInfoVo> queryById(@RequestParam(name = "id", required = true) String id) {
        RepairInfoVo vo = repairInfoService.getVoById(id);
        return Result.ok(vo);
    }


    @CheckLogin
    @ApiOperation(value = "维修信息-查询进行中的合同信息", notes = "维修信息-查询进行中的合同信息")
    @GetMapping(value = "/leaseContractList")
    public Result<List<RepairAsseVo>> leaseContractList(HttpServletRequest req) {
        String attentionId = JwtUtil.getUserNameByToken(req);
        List<String> customerIds = customerAttentionService.queryCustomerIdsByAttentionId(attentionId);
        if (customerIds == null || customerIds.size() == 0) {
            return Result.ok(new ArrayList<>());
        }
        LambdaQueryWrapper<LeaseContractInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(LeaseContractInfo::getStatus, LeaseContractStatusEnum.TAKE_EFFECT.getStatus(), LeaseContractStatusEnum.RENEW.getStatus());

//        queryWrapper.in(LeaseContractInfo::getCustomerId, customerIds);
        queryWrapper.and(i -> i.apply(QueryGenerator.getCustomerSql(customerIds)));
        List<LeaseContractInfo> leaseContractInfoList = leaseContractInfoService.list(queryWrapper);
        List<RepairAsseVo> list = new ArrayList<>();
        if (leaseContractInfoList != null) {
            leaseContractInfoList.forEach(info -> {
                if (StringUtils.isNotBlank(info.getAssetId())) {
                    String[] assetIdArr = info.getAssetId().split(CommonConstant.DEFAULT_SEPARATOR);
                    if (assetIdArr.length > 1) {
                        for (int i = 0; i < assetIdArr.length; i++) {
                            RepairAsseVo vo = new RepairAsseVo();
                            vo.setAssetId(assetIdArr[i]);
                            list.add(vo);
                        }
                    } else {
                        if (StringUtils.isNotBlank(info.getAssetSubIds())) {
                            String[] assetSubIdArr = info.getAssetSubIds().split(CommonConstant.DEFAULT_SEPARATOR);
                            for (int i = 0; i < assetSubIdArr.length; i++) {
                                RepairAsseVo vo = new RepairAsseVo();
                                vo.setAssetId(assetIdArr[0]);
                                vo.setAssetSubIds(assetSubIdArr[i]);
                                list.add(vo);
                            }
                        } else {
                            RepairAsseVo vo = new RepairAsseVo();
                            vo.setAssetId(assetIdArr[0]);
                            list.add(vo);
                        }

                    }
                }
            });
        }

        return Result.ok(list);
    }
}
